package com.changfen.util;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Map;

/**
 * @author 86180
 * @Classname OkHttpUtil
 * @Description TODO
 * @Date 2022/8/28 9:36
 */
public class OkHttpUtil {
    private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);

    /**
     * 根据map获取get请求参数
     *
     * @param queries
     * @return
     */
    private static StringBuffer getQueryString(String url, Map<String, String> queries) {
        StringBuffer sb = new StringBuffer(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = queries.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        return sb;
    }

    /**
     * 调用okhttp的newCall方法
     *
     * @param request
     * @return
     */
    private static String execNewCall(Request request) {
        Response response = null;
        try {
            OkHttpClient okHttpClient = SpringUtils.getBean(OkHttpClient.class);
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            logger.error("okhttp3 put error >> ex = {}", e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

    /**
     * get
     *
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return
     */
    public static String get(String url, Map<String, String> queries) {
        StringBuffer sb = getQueryString(url, queries);
        Request request = new Request.Builder()
                .url(sb.toString())
                .header("cookie","device_id=6aa70eca7351d27833e57b92945c9173; s=d4120di1v7; xq_a_token=e31f6fe87cb3811caf245837d372d8080b8aa71f; xqat=e31f6fe87cb3811caf245837d372d8080b8aa71f; xq_r_token=3ad0c5218061554069531a3eb2c89f7017fa7c1b; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOjI4MDMwOTI4ODIsImlzcyI6InVjIiwiZXhwIjoxNjY0MTk5OTAzLCJjdG0iOjE2NjE2MDc5MDMwNDUsImNpZCI6ImQ5ZDBuNEFadXAifQ.d1KVrLJ1_1nEjK7Dxs5KqpB8_OctUZBwSC69kJ9q_ZpvlHFXcmrvq8PtKt3Ry_2WvPcin_hAe44gqdl_cq8h_XpQ-_tQ4Z0sJm7LEqVFZuuLGBvboUaCAcDFHoEennRSWntZVa1RDAthob66y3uJcDMzoLZdmp8nXqXIZX3drDMNCnXsdyQNSLQwz7PatK1LBcx4isBN4o-VvznBruNActM1INgj_-VhNKoJgIUQyok2NN6u8zwNqsX8NXlgvCNRLYontdOK_unHIKOHO0t_Whua8GpkSEWls9WGV54a7jknq14o8iyEK3OGQA5gp48o2dCvh1gj91LzdWwhPOYxLQ; xq_is_login=1; u=2803092882; bid=02bf89a057ed68bc4aea5c6c32398fc7_l7bygya3; Hm_lvt_1db88642e346389874251b5a1eded6e3=1661607892,1661610279,1661650977; snbim_minify=true; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1661650982")
                .build();
        return execNewCall(request);
    }

    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return
     */
    public static String postFormParams(String url, Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        return execNewCall(request);
    }


    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
     * 参数一：请求Url
     * 参数二：请求的JSON
     * 参数三：请求回调
     */
    public static String postJsonParams(String url, String jsonParams) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        return execNewCall(request);
    }

    /**
     * Post请求发送xml数据....
     * 参数一：请求Url
     * 参数二：请求的xmlString
     * 参数三：请求回调
     */
    public static String postXmlParams(String url, String xml) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .header("cookie","device_id=6aa70eca7351d27833e57b92945c9173; s=d4120di1v7; xq_a_token=e31f6fe87cb3811caf245837d372d8080b8aa71f; xqat=e31f6fe87cb3811caf245837d372d8080b8aa71f; xq_r_token=3ad0c5218061554069531a3eb2c89f7017fa7c1b; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOjI4MDMwOTI4ODIsImlzcyI6InVjIiwiZXhwIjoxNjY0MTk5OTAzLCJjdG0iOjE2NjE2MDc5MDMwNDUsImNpZCI6ImQ5ZDBuNEFadXAifQ.d1KVrLJ1_1nEjK7Dxs5KqpB8_OctUZBwSC69kJ9q_ZpvlHFXcmrvq8PtKt3Ry_2WvPcin_hAe44gqdl_cq8h_XpQ-_tQ4Z0sJm7LEqVFZuuLGBvboUaCAcDFHoEennRSWntZVa1RDAthob66y3uJcDMzoLZdmp8nXqXIZX3drDMNCnXsdyQNSLQwz7PatK1LBcx4isBN4o-VvznBruNActM1INgj_-VhNKoJgIUQyok2NN6u8zwNqsX8NXlgvCNRLYontdOK_unHIKOHO0t_Whua8GpkSEWls9WGV54a7jknq14o8iyEK3OGQA5gp48o2dCvh1gj91LzdWwhPOYxLQ; xq_is_login=1; u=2803092882; bid=02bf89a057ed68bc4aea5c6c32398fc7_l7bygya3; Hm_lvt_1db88642e346389874251b5a1eded6e3=1661607892,1661610279,1661650977; snbim_minify=true; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1661650982")
                .build();
        return execNewCall(request);
    }
}
//endregion
